import { createVNode, nextTick, render, type AppContext, type ComponentPublicInstance } from 'vue'
import { useDynamicDialogService } from './service'

let seed = 1
export const useDynamicDialog = () => {
  const getAppContext = (context?: AppContext | undefined) => {
    if (!context) {
      return context
    }
    const service = useDynamicDialogService()
    if (service == undefined) {
      return undefined
    }
    return service.appContext
  }

  const open = (component: any, options: any | undefined = undefined) => {
    const uid = seed++
    const userOnClosed = options?.onClosed

    const container = document.createElement('div')
    container.id = `dynamic_dialog_container_${uid}`
    const props = {
      ...options
    }

    const vnode: any | undefined = createVNode(component, {
      ...props,
      onClosed: () => {
        userOnClosed?.()
        // 关闭时移出组件
        render(null, container)
        nextTick(() => {
          document.body.removeChild(container)
        })
      }
    })

    vnode.appContext = getAppContext()

    render(vnode, container)

    document.body.appendChild(container)

    const vm = vnode.component!
    const instance = {
      vnode,
      vm,
      props: (vnode.component as any).props,
      close: () => {
        vnode.props.onClosed()
      }
    }

    return instance
  }

  return {
    open
  }
}
